package org.sagitta.httprpc.pox.adaptor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sagitta.httprpc.RequestUnmarshaller;
import org.sagitta.httprpc.exception.RPCException;


class POXRequestUnmashaller implements RequestUnmarshaller {

	private static final Log log = LogFactory.getLog(POXRequestUnmashaller.class);
	private Unmarshaller u;

	public POXRequestUnmashaller(JAXBContext context) throws JAXBException {
		u = context.createUnmarshaller();
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T unmashal(Class<T> requestClass, InputStream data) throws RPCException {
		try {
			String xml = getRequestText(data);
			if (log.isDebugEnabled()) {
				log.debug("Post message: " + xml);
			}
			JAXBElement<T> eelement = u.unmarshal(new StreamSource(new StringReader(xml)), requestClass);
			return eelement.getValue();
		} catch (JAXBException e) {
			e.printStackTrace();
			throw new RPCException(RPCException.REQUESTMASHLLERROR);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RPCException(RPCException.REQUESTMASHLLERROR);
		}
	}

	private String getRequestText(InputStream is) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String s = reader.readLine();
		while (s!=null) {
			sb.append(s);
			s = reader.readLine();
		}
		return POXUtil.consumeBOM(sb.toString());
	}


}
